// ignore_for_file: file_names, slash_for_doc_comments, must_call_super, unnecessary_overrides, override_on_non_overriding_member, must_be_immutable, prefer_const_constructors, sized_box_for_whitespace, avoid_unnecessary_containers, avoid_print

import 'dart:convert';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:mybase/base/abstract/IFFR.dart';
import 'package:mybase/base/abstract/IFFRefresh.dart';
import 'package:mybase/base/abstract/IFFScaffold.dart';
import 'package:mybase/base/tool/empty/FFEmpty.dart';
import 'package:mybase/base/tool/entitylog/MyEntityTestRun.dart';
import 'package:mybase/base/tool/file/FFDirectory.dart';
import 'package:mybase/base/tool/file/FFile.dart';
import 'package:mybase/base/widget/layout/FFLineContainer.dart';
import 'package:mybase/base/widget/layout/FFTextButton.dart';
import 'package:mybase/base/widget/page/FFScaffold.dart';
import 'package:mybase/base/tool/extension/FFListExt.dart';
import 'package:webview_window_example/config/ConfigVal.dart';
import 'package:webview_window_example/textField/FFMoreTextField.dart';
import 'package:webview_window_example/textField/FFTextField.dart';
import 'package:webview_window_example/utils/navi/AppNavi.dart';

class JsonToEntityPage extends FFScaffold {
  String? name;

  JsonToEntityPage({
    Key? key,
    this.name,
  }) : super(key: key);

  @override
  JsonToEntityPageState createState() => JsonToEntityPageState();
}

class JsonToEntityPageState extends FFScaffoldState with MFFScaffold {
  /**固定写法 */
  @override
  IFFScaffold get iffScaffold => this;

  @override
  JsonToEntityPage get widget => super.widget as JsonToEntityPage;

  @override
  IFFRefresh? get iffRefresh => refresh;
  late JsonToEntityPageRefresh refresh = JsonToEntityPageRefresh(state: this);

  /**固定写法end */

  String? targetDir;
  String? className;

  String? jsonValue;
  TextEditingController controller = TextEditingController();

  @override
  void ffInitState() {
    super.ffInitState();
  }

  @override
  Widget? ffNavi(BuildContext context) {
    return AppNavi.createNavi(
      context,
      title: "json生成Entity",
    );
  }

  @override
  Widget? ffBody(BuildContext context) {
    return FFLineContainer(
      direction: Axis.vertical,
      children: [
        Container(
          width: MediaQuery.of(context).size.width,
          height: 400,
          color: Colors.pink,
          padding: EdgeInsets.symmetric(horizontal: 10, vertical: 4),
          child: FFMoreTextField(
            cursorColor: Colors.white,
            placeStr: "请输入json格式",
            controller: controller,
            needCancelBtn: false,
            onValid: (bool valid, String value) {},
            min: 1,
            max: 999999999999,
            maxLines: 9999999999,
          ),
        ),
        FFTextButton(
          unconstrainedBox: true,
          text: "格式化Json",
          padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
          color: Colors.red,
          margin: EdgeInsets.only(top: 8),
          onClick: () async {
            if (FFEmpty.stringIsEmpty(controller.text)) {
              SmartDialog.showToast("无须格式化");
              return;
            }

            try {
              var map = jsonDecode(controller.text);
              //格式化输出json
              String jsonStr = JsonEncoder.withIndent('  ').convert(map);
              controller.text = jsonStr;
              SmartDialog.showToast("格式化成功",
                  displayTime: Duration(milliseconds: 200));
            } catch (e) {
              print("出错了 $e");
              SmartDialog.showToast("格式化出错，不是标准的json");
            }
          },
        ),
        FFTextButton(
          unconstrainedBox: true,
          text: "选择生成的目录",
          padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
          color: Colors.red,
          margin: EdgeInsets.only(top: 8),
          onClick: () async {
            String? selectedDirectory = await FilePicker.platform
                .getDirectoryPath(initialDirectory: ConfigVal.osDir);

            if (!(await FFDirectory.isExistDirectory(
                selectedDirectory ?? ""))) {
              SmartDialog.showToast("目标目录选择失败");
              return;
            }

            targetDir = selectedDirectory;
            setState(() {});
          },
        ),
        FFTextButton(
          text: targetDir,
          maxLines: 1000,
        ),
        FFTextButton(
          unconstrainedBox: true,
          text: "自定义类名",
          padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
          color: Colors.red,
          margin: EdgeInsets.only(top: 8),
        ),
        Container(
          width: 200,
          height: 36,
          color: Colors.pink,
          padding: EdgeInsets.symmetric(horizontal: 10),
          child: FFTextField(
            placeStr: "请输入类名",
            needCancelBtn: false,
            onValid: (bool valid, String value) {
              className = value;
            },
            min: 1,
            max: 99,
          ),
        ),
        FFTextButton(
          unconstrainedBox: true,
          text: "创建",
          padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
          color: Colors.red,
          margin: EdgeInsets.only(top: 8),
          onClick: () async {

            if (FFEmpty.stringIsEmpty(controller.text)) {
              SmartDialog.showToast("json内容为空");
              return;
            }

            if (!(await FFDirectory.isExistDirectory(targetDir ?? ""))) {
              SmartDialog.showToast("生成的目录不存在");
              return;
            }

            if (FFEmpty.stringIsEmpty(className)) {
              SmartDialog.showToast("自定义类名不能为空");
              return;
            }

            //验证json
            bool isJson = true;
            Map<dynamic, dynamic> map = {};
            try {
              json.decode(controller.text);
              dynamic mapTemp = jsonDecode(controller.text);
              isJson = map is Map;
              if (isJson) {
                map = mapTemp;
              }
            } catch (e) {
              isJson = false;
            }

            if (isJson == false) {
              SmartDialog.showToast("不是标准的json格式");
              return;
            }

            String result = await MyEntityTestRun.createEntityCodeStr(
                map: map, targetDir: targetDir!, entityClassName: className!);
            SmartDialog.showToast(result);
          },
        ),
      ],
    );
  }
}

class JsonToEntityPageRefresh with MFFRefresh {
  JsonToEntityPageState state;

  JsonToEntityPageRefresh({required this.state});

  @override
  bool? ffCanRefreshHead() {
    return true;
  }

  @override
  ffRefresh(bool isHead) {
    ffRefreshResult(isHead, test, state);
  }

  //具体请求业务
  Future<IFFR> test(IRefreshParam? iRefreshParam) async {
    List? list;
    await Future.wait([
      //HomeApi.index_recentlyPlayed(),
    ]).then((value) {
      list = value;
    });

    IFFR? r = list?.safeValue(0);
    return r ?? R(rStatus: RStatus.result);
  }
}
